// 引入模块
const gulp = require('gulp');
const sass = require('gulp-sass');
const browserSync = require('browser-sync');
const cssnano = require('gulp-cssnano');
const uglify = require('gulp-uglify');
const plumber = require('gulp-plumber');
const babel = require('gulp-babel');
const useref = require('gulp-useref');
const gulpIf = require('gulp-if');
const autoprefixer = require('gulp-autoprefixer');
const del = require('del');
const runSequence = require('run-sequence');

// 图片压缩
const imagemin = require('gulp-imagemin');
const mozJpeg = require('imagemin-mozjpeg');
const pngQuant = require('imagemin-pngquant');



// 定义任务
gulp.task('styles', () => {
    return gulp.src('app/styles/*.scss')
        .pipe(plumber())
        .pipe(sass({
            outputStyle: 'expanded'
        }))
        .pipe(autoprefixer({
            browsers: ['> 1%', 'last 2 versions', 'Firefox ESR']
        }))
        .pipe(gulp.dest('.tmp/css'))
        .pipe(browserSync.reload({
            stream: true
        }));
});

gulp.task('scripts', () => {
    return gulp.src('app/scripts/**/*.js')
        .pipe(plumber())
        .pipe(babel({
            presets: ['env']
        }))
        .pipe(gulp.dest('.tmp/js'))
        .pipe(browserSync.reload({
            stream: true
        }));
});

gulp.task('images', () => {
    return gulp.src('app/images/**/*.{png,jpg,gif,svg}')
        .pipe(imagemin([
            mozJpeg({
                quality: 30
            }),
            pngQuant({
                quality: 10
            })
        ]))
        .pipe(gulp.dest('dist/images'));
});

gulp.task('html', () => {
    return gulp.src('app/**/*.html')
        .pipe(useref({
            searchPath: '.tmp'
        }))
        .pipe(gulpIf(/\.css$/, cssnano()))
        .pipe(gulpIf(/\.js$/, uglify({
            compress: {
                drop_console: true
            }
        })))
        .pipe(gulp.dest('dist'));
});

// 清理生成
gulp.task('clean', () => {
    return del(['dist', '.tmp']);
});

// 自建服务器
gulp.task('serve', () => {
    runSequence('clean', ['styles', 'scripts'], () => {
        browserSync({
            port: 9000,
            server: {
                baseDir: ['.tmp', 'app']
            }
        });

        gulp.watch('app/styles/*.scss', ['styles']);
        gulp.watch('app/scripts/**/*.js', ['scripts']);
        gulp.watch('app/**/*.html', browserSync.reload);
    });
});

// 构建任务
gulp.task('build', () => {
    runSequence('clean', ['scripts', 'styles', 'images'], 'html', () => {
        browserSync.init({
            notify: false,
            port: 9000,
            server: {
                baseDir: ['dist']
            }
        });
    });
});